package com.devops.admin.controller;

import com.devops.admin.service.DOSLogsService;
import com.devops.admin.util.TailLogUtil;
import com.devops.common.utils.SpringUtil;
import io.fabric8.kubernetes.client.dsl.LogWatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName WebSocketController
 * @Description TODO
 * @Author heyabo
 * @Date 2022/4/27 16:57
 * @Version 1.0
 **/
@ServerEndpoint("/websocket/{id}/{podName}/{type}")
@Component
@Slf4j
public class WebSocketController {
    private final ConcurrentHashMap<String, TailLogUtil> sessionThreads = new ConcurrentHashMap<>();

    /**
     * 新的WebSocket请求开启
     */
    @OnOpen
    public void onOpen(@PathParam("id") int id,
                       @PathParam("podName") String podName,
                       @PathParam("type") int type,
                       Session session) {
        sendLog(id, podName, type, session);
    }

    private void sendLog(int id, String podName, int type, Session session) {

        DOSLogsService DOSLogsService = (DOSLogsService) SpringUtil.getBean("logService");
        LogWatch logWatch = DOSLogsService.getK8sClusterPodLog(id, podName, type);
        BufferedReader reader = new BufferedReader(new InputStreamReader(logWatch.getOutput()));

        TailLogUtil thread = new TailLogUtil(session, reader, logWatch);
        sessionThreads.put(session.getId(), thread);
        thread.start();
    }

    /**
     * WebSocket请求关闭
     */
    @OnClose
    public void onClose(Session session) {

        try {
            TailLogUtil thread = sessionThreads.remove(session.getId());
            if (thread != null) {
                thread.stopRunning();
                // 等待线程最多3秒钟
                thread.join(3000);
            }
        } catch (Exception e) {
            log.error("关闭websocket失败");
            e.printStackTrace();
        }

        log.info("关闭日志查看的websocket连接");
    }

    @OnError
    public void onError(Throwable thr) {
        log.error("websocket error." + thr);
    }

    @OnMessage
    public String sendMessage(String msg){
        return msg;
    }
}
